package com.utils;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;

/**
 * @author: 晓帆
 * @description:
 * @create: 2021-06-10 20:01
 **/
public class upload {
    private static String realPath=null;
    public static String getMap(HttpServletRequest request) throws Exception {

        //维护一个map使用Beanutils
//        HashMap<String, Object> map = new HashMap<>();
        if (ServletFileUpload.isMultipartContent(request)){
            //工厂类
            DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
            //获取ServletFileUpload
            ServletFileUpload fileUpload=new ServletFileUpload(diskFileItemFactory);
            try {
                //ServletFileUpload解析request获取信息（解析Input标签）
                List<FileItem> fileItems = fileUpload.parseRequest(request);
                for (FileItem fileItem : fileItems) {
                        System.out.println(fileItem);
                    realPath = fileUpload(fileItem, request);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return realPath;
    }
    private static String fileUpload(FileItem fileItem, HttpServletRequest request) throws Exception {

        if (fileItem.getName()==null||fileItem.getName().length()==0){
            return null;
        }
        String realPath = request.getServletContext().getRealPath("imgs/" + fileItem.getName());
        File file = new File(realPath);
        //如果有不存在的文件夹，创建它
        if (!file.getParentFile().exists()){
            file.getParentFile().mkdirs();
        }
        //上传
        fileItem.write(file);
        //获取网络路径：/upload/imgs/资源名
        String realname="imgs/" + fileItem.getName();
        //fileItem.getFieldName()：获取<input>标签的name
//        map.put(fileItem.getFieldName(),realname);
        return realname;
    }

}
